package com.zjitc;

import java.util.concurrent.Executors;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/16 14:00
 * @description: 模拟秒杀的测试
 */
public class SecondKillTest {

  private JedisPool pool;
  private static final String SECOND_KILL_PRODUCT_NAME = "SECOND_KILL_U";

  @Before
  public void simulateInit() {
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxTotal(20);
    config.setMinIdle(10);
    config.setBlockWhenExhausted(true);
    this.pool = new JedisPool(config, "localhost");

    try (Jedis jedis = this.pool.getResource()) {
      jedis.set(SECOND_KILL_PRODUCT_NAME, "200");
    }
  }

  @Test
  public void simulateSecondKillTest() {
    // 模拟并发操作
    for (int i = 0; i < 10000; i++) {
      int index = i;
      Executors.newSingleThreadExecutor().submit(()->{
        try (Jedis jedis = this.pool.getResource()) {
          Long remainCount = jedis.decr(SECOND_KILL_PRODUCT_NAME);
          if (remainCount >= 0) {
            System.out.println("第" + index + "顾客第" + (200 - remainCount) + "购买");
          }
        }
      });
    }
  }
}
